package com.zero.xiaodai.utils;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;

public class GridFSFileUtil {

	private static void uploadFile(MultipartHttpServletRequest request) {
		try {
			
			
			Map<String, Object> map = new HashMap<>();
			StringBuffer path = new StringBuffer();
			MultipartFile file = request.getFile("file");
			//上面可由控制器中转换为file之后再调用此方法
			
			String fileName = file.getOriginalFilename();
			map.put("fileName", fileName);
			Long size = file.getSize();
			map.put("fileSize", size);
			String format = fileName.substring(fileName.lastIndexOf("."));
			fileName = UUID.randomUUID().toString() + format;
			GridFS gridFS = new GridFS(MongoDB.getDB(MongoProperties.DB_NAME), MongoProperties.COLLECTIONS_NAME);
			GridFSFile fsFile = gridFS.createFile(file.getInputStream(), fileName);
			fsFile.save();
			path.append("/" + MongoProperties.NGINX_PATH + "/" + fileName);
			/*
			 * List<MultipartFile> files=request.getFiles("file"); for(MultipartFile
			 * file:files) { if(path.length()>0) { path.append(","); }
			 * 
			 * }
			 */

			map.put("filePath", path);
			//可根据需求定返回内容
		} catch (Exception e) {
			// TODO: handle exception
		}

	}
	
	
	private static void downloadFile(String fileName,HttpServletResponse response, HttpServletRequest request) {
		try {
			fileName=fileName.substring(fileName.lastIndexOf("/")+1);
			// 获取fs的根节点
			GridFS gridFS = new GridFS(MongoDB.getDB(MongoProperties.DB_NAME), MongoProperties.COLLECTIONS_NAME);
			// 解析id
			//String[] key = parseDbKey(id);
			// 取objectId
			//ObjectId objectId = new ObjectId(key[0]);
			// 取表名
			// String CollectionsName=key[1];
			// 通过id查询
			//GridFSDBFile file = fs.find(objectId);
			// 通过文件名称查询
			DBObject query=new BasicDBObject("filename",fileName);
			GridFSDBFile file = gridFS.findOne(query);
			// GridFSDBFile file = fs.findOne("lvxing");
			// 输出文件
			
			
			
			response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
			
			OutputStream outputStream = response.getOutputStream();
			file.writeTo(outputStream);
			outputStream.flush();
			outputStream.close();
			
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.error("下载文件异常",e);
		}
	}

}
